<template>
  <div class="xiecheng">
    <div class="admin_main_block">
      <div class="admin_main_block_top">
        <div class="admin_main_block_left">
          <div>
            <el-dropdown class="more">
              <el-button type="success" icon="Plus">
                {{ i18n('common.create') }}
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="router.push({ name: 'module_business_client_form' })">
                    手动填写信息
                  </el-dropdown-item>

                  <el-dropdown-item @click="dialogVisible = true;loadQrcodeUrl()">
                    客户扫码添加
                  </el-dropdown-item>

                  <el-dropdown-item @click="router.push({ name: 'module_business_client_publicity_list' })" divided>
                    从公众库添加
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <div class="admin_main_block_right">
          <div>
            <el-button
              type="danger"
              icon="Delete"
              @click="deleteHandle()">
              {{ i18n('common.batch_delete') }}
            </el-button>
          </div>
        </div>
      </div>

      <div class="general-situation">
        <div>
          <el-tag class="float-right" type="info" size="small" effect="dark" round>
            {{ totalPage }}
          </el-tag>
          <h5 class="float-right mr10">我的客户</h5>
        </div>
      </div>

      <div class="admin_main_block_select color" style="padding: 0 20px;">
        <el-form label-position="right" label-width="auto">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item :label="i18n('client.name')">
                <el-input v-model="dataForm.name" :placeholder="$t('common.please_input') + $t('contact.name')"  clearable @change="getDataList(model)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item :label="i18n('client.level')">
                <el-radio-group v-model="dataForm.level" @change="getDataList(model)">
                  <el-radio label="">{{ i18n('common.all') }}</el-radio>
                  <el-radio v-for="(v, k) in levelList" :key="k" :label="v.value">
                    {{ v.value }} - {{ v.text }}
                    <span class="red">({{ v.total }})</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item :label="i18n('example.industry_id')">
                <el-cascader v-model="dataForm.industry_id" :placeholder="$t('common.please_select')+$t('example.industry_id')" :options="industryList" :props="levelProps" clearable @change="getDataList(model)">
                  <template v-slot="{ node, data }">
                    <span>{{ data.title }}</span>
                    <span class="float-right">{{ data.total }}</span>
                  </template>
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item :label="i18n('client.integrity_score')">
                <el-radio-group v-model="dataForm.integrity_score" @change="getDataList(model)">
                  <el-radio label="">{{ i18n('common.all') }}</el-radio>
                  <el-radio v-for="(v, k) in integrityScoreList" :key="k" :label="v.value">
                    {{ v.text }}
                    <span class="red">({{ v.total }})</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item :label="i18n('demand.demand_type')">
                <el-select
                  v-model="dataForm.demand__demand_type"
                  :placeholder="i18n('common.please_select') + i18n('demand.demand_type')" clearable @change="getDataList(model)">
                  <el-option v-for="(v, k) in demandTypeList" :label="v.text" :key="k" :value="v.value">
                    <span class="float-left">{{ v.text }}</span>
                    <span class="float-right">{{ v.total }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item :label="i18n('contact.access_authority')">
                <el-radio-group v-model="dataForm.access_authority" @change="getDataList(model)">
                  <el-radio label="">{{ i18n('common.all') }}</el-radio>
                  <el-radio v-for="(v, k) in accessAuthorityList" :key="k" :label="v.value">
                    {{ v.text }}
                    <span class="red">({{ v.total }})</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item :label="i18n('client.user_id')">
                <el-select
                  v-model="dataForm.user_id"
                  :placeholder="i18n('common.please_select') + i18n('client.user_id')" clearable @change="getDataList(model)">
                  <el-option v-for="(v, k) in userList" :label="v.nickname" :key="k" :value="v.id">
                    <span class="float-left">{{ v.nickname }}</span>
                    <span class="float-right">{{ v.total }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item :label="i18n('client.trace_time')">
                <el-radio-group v-model="dataForm.trace_time" @change="getDataList(model)">
                  <el-radio label="">{{ i18n('common.all') }}</el-radio>
                  <el-radio v-for="(v, k) in traceTimeList" :key="k" :label="v.value">
                    {{ v.text }}
                    <span class="red">({{ v.total }})</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="admin_table_main color">
        <el-table :data="dataList" v-loading="dataListLoading" @selection-change="selectionChangeHandle" stripe>
          <el-table-column type="selection" header-align="center" align="center">
          </el-table-column>

          <el-table-column prop="id" :label="i18n('common.id')" width="70">
          </el-table-column>

          <el-table-column :label="i18n('client.info')" min-width="240">
            <template v-slot="scope">
              <dl class="table_dl">
                <dd class="table_dl_dd_all_30">
                  <el-link @click="router.push({ name: 'module_business_client_mine_view', query: { id: scope.row.id } })" :underline="false">
                    {{ scope.row.name }}
                    <span class="ml2" v-if="!isEmpty(scope.row.share)">
                      <el-text type="primary" tag="sup" size="small">共享</el-text>
                    </span>
                    <el-icon class="mr5"><ArrowRight /></el-icon>
                    <el-icon class="mr10" color="#67C23A" v-if="scope.row.access_authority"><SuccessFilled /></el-icon>
                  </el-link>
                </dd>
                <dd class="table_dl_dd_all_16_gray">
                  {{ scope.row.level.value }}级 | {{ scope.row.industry_info }}
                </dd>
              </dl>
            </template>
          </el-table-column>

          <el-table-column :label="i18n('client.new_demand')" width="150">
            <template v-slot="scope">
              <dl class="table_dl" v-if="scope.row.latest_demand">
                <dd class="table_dl_dd_all_30">
                  {{ scope.row.latest_demand.demand_time }}
                </dd>
                <dd class="table_dl_dd_all_16_gray">
                  {{ scope.row.latest_demand.demand_type.text }}
                </dd>
              </dl>
              <span v-else>
                {{ i18n('common.empty') }}
              </span>
            </template>
          </el-table-column>

          <el-table-column :label="i18n('client.new_record')" width="160">
            <template v-slot="scope">
              <dl class="table_dl" v-if="scope.row.latest_trace">
                <dd class="table_dl_dd_all_30">
                  {{ scope.row.latest_trace.create_time_text }}
                </dd>
                <dd class="table_dl_dd_all_16_gray">
                  {{ scope.row.latest_trace.type.text }}
                </dd>
              </dl>
              <span v-else>
                {{ i18n('common.empty') }}
              </span>
            </template>
          </el-table-column>

          <el-table-column :label="i18n('client.integrity_score')" width="100">
            <template v-slot="scope">
              <span :class="scope.row.integrity_score.value < 30 ? 'red' : (scope.row.integrity_score.value < 60 ? 'orange' : (scope.row.integrity_score.value < 90 ? 'blue' : 'green1'))">
                {{ scope.row.integrity_score.text }} ({{scope.row.integrity_score.value}})
              </span>
            </template>
          </el-table-column>

          <el-table-column :label="i18n('contact.salesperson')" width="150">
            <template v-slot="scope">
              <dl class="table_dl" v-if="scope.row.user">
                <dt>
                  <el-avatar :size="45" :src="scope.row.user.avatar" />
                </dt>
                <dd class="table_dl_dd_all_30">
                  {{ scope.row.user.nickname }}
                </dd>
                <dd class="table_dl_dd_all_16_gray" v-if="scope.row.user.detail">
                  {{ scope.row.user.detail.position }}
                </dd>
              </dl>
            </template>
          </el-table-column>

          <el-table-column :label="$t('common.status')" width="80">
            <template v-slot="scope">
              <el-switch
                v-model="scope.row.status.value"
                active-value="1"
                inactive-value="2"
                size="large"
                inline-prompt
                :active-text="$t('common.enable')"
                :inactive-text="$t('common.disable')"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                @change="handleStatus($event, scope.row.id, 'status')">
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column prop="create_time_text" :label="i18n('common.create_time')" width="100">
          </el-table-column>

          <el-table-column :label="i18n('common.handle')" fixed="right" width="200">
            <template v-slot="scope">
              <el-button
                type="danger"
                icon="Delete"
                @click="deleteHandle(scope.row.id)">
                {{ i18n('common.delete') }}
              </el-button>

              <el-dropdown class="more">
                <el-button icon="More">
                  {{ i18n('common.more') }}
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="router.push({ name: 'module_business_client_mine_view', query: { id: scope.row.id } })">
                      {{ i18n('client.view') }}
                    </el-dropdown-item>

                    <el-dropdown-item @click="router.push({ name: 'module_business_contact_list_list', query: { client_id: scope.row.id } })">查看联系人</el-dropdown-item>
                    <el-dropdown-item @click="router.push({ name: 'module_business_demand_list_list', query: { client_id: scope.row.id } })">查看需求</el-dropdown-item>
                    <el-dropdown-item @click="router.push({ name: 'module_business_client_trace_list', query: { client_id: scope.row.id } })">
                      查看跟踪记录
                    </el-dropdown-item>

                    <el-dropdown-item @click="router.push({ name: 'module_business_client_list_transfer', query: { id: scope.row.id } })" divided :disabled="!isEmpty(scope.row.share)">
                      转移给其他人
                    </el-dropdown-item>
                    <el-dropdown-item @click="changeHandle(scope.row.id)">
                      转移至公共库
                    </el-dropdown-item>
                    <el-dropdown-item @click="router.push({ name: 'module_business_client_share_form', query: { id: scope.row.id } })" :disabled="!isEmpty(scope.row.share)">
                      共享该客户
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div class="admin_table_main_pagination">
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :page-size="pageSize"
            :total="totalPage"
            :current-page="pageIndex"
            background
            layout="prev, pager, next,jumper,total">
          </el-pagination>
        </div>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="客户扫码注册" width="500" center>
      <div class="text-center mt20">
        <el-image class="qrcode" :src="qrcode_url"/>
      </div>
      <template #footer>
        <div class="dialog-footer mb20">
          <el-button @click="copyToClipboard">复制二维码</el-button>
          <el-button type="primary" @click="downloadQrcode">
            下载二维码
          </el-button>
        </div>

        <div class="alert">
          <div class="title">
            将二维码发给客户微信，扫码即可完成注册！
          </div>
          <div class="content">
            二维码有效期为24小时，过期后需要重新获取
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="client-list">
  import { useBase } from "@/hooks/base/useBase"
  import { useTable } from "@/hooks/table/useTable"
  import { isEmpty } from '@/utils/validate'

  const { router, query, i18n, isAuth } = useBase()

  const model = ref('business/client')

  const levelProps = ref({
    label: 'title',
    value: 'id',
    emitPath: false,
    checkStrictly: false
  })

  const dialogVisible = ref(false)
  const qrcode_url = ref('')

  const levelList = ref([])
  const industryList = ref([])
  const demandTypeList = ref([])
  const integrityScoreList = ref([])
  const accessAuthorityList = ref([])
  const traceTimeList = ref([])
  const userList = ref([])

  const dataForm = reactive([
    'type',
    'name',
    'level',
    'industry_id',
    'integrity_score',
    'access_authority',
    'demand__demand_type',
    'trace_time',
    'user_id',
    'status',
    'create_time',
  ])

  const {
    dataList,
    pageIndex,
    pageSize,
    totalPage,
    dataListLoading,
    sizeChangeHandle,
    currentChangeHandle,
    selectionChangeHandle,
    getDataList,
    handleStatus,
    deleteHandle,
  } = useTable(model.value, dataForm)

  const loadSearchList = () => {
    $http({
      url: $http.adornUrl('/business/client/search/data'),
      method: 'get',
      params: $http.adornParams({
        type: dataForm.type
      }),
    }).then(({data}) => {
      if (data && data.status === 200) {
        levelList.value = data.data.client_level
        demandTypeList.value = data.data.demand_type
        integrityScoreList.value = data.data.complete_level
        accessAuthorityList.value = data.data.access_authority
        traceTimeList.value = data.data.trace_time
        userList.value = data.data.user
        industryList.value = data.data.industry
      } else {
        $message.error(data.message)
      }
    })
  }

  const loadQrcodeUrl = () => {
    $http({
      url: $http.adornUrl('/business/qrcode/official/data'),
      method: 'get',
      params: $http.adornParams({
        event: 'client_register',
      }),
    }).then(({ data }) => {
      if (data && data.status === 200) {
        qrcode_url.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const copyToClipboard = () => {
    navigator.clipboard.writeText(qrcode_url.value);
    dialogVisible.value = false
  }

  const downloadQrcode = () => {
    if(qrcode_url.value) {
      window.open(qrcode_url.value)
    }
  }

  // 更改客户所属人
  const changeHandle = (id) => {
    $http({
      url: $http.adornUrl(`${model.value}/publicity`),
      method: 'post',
      data: {
        id: id
      },
    }).then(({ data }) => {
      if (data && data.status === 200) {
        $message({
          message: i18n('common.handle_success'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            getDataList()
          },
        })
      } else {
        $message.error(data.message)
      }
    })
  }

  onMounted(() => {
    dataForm.type = 2

    getDataList(model)

    loadSearchList()
  })
</script>

<style scoped lang="scss">
  .qrcode {
    width: 10vw;
    height: 10vw;
  }
  .alert {
    text-align: left;
    padding: 10px 5vw;
    color: var(--el-color-warning);
    background-color: var(--el-color-warning-light-9);

    .title {
      font-size: 13px;
      font-weight: bold;
    }
    .content {
      font-size: 12px;
      margin-top: 5px;
    }
  }
</style>
